package cn.edu.fzu.homemaking.helper;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.springframework.stereotype.Component;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;

/**
 * pdf生成工具 由于linux环境下,可能没有相应的中文字体,所以字体文件放在/fonts目录下
 * 
 * @author fangxin
 * @date 2023/3/26
 */
@Component
public class PdfHelper extends XMLWorkerFontProvider {

    public PdfHelper() {
        super(PdfHelper.class.getResource("/fonts").getPath());
    }


    //将content生成pdf导入到os中
    public void pdf(byte[] content, OutputStream os) throws DocumentException, IOException {
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, os);
        document.open();
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(content), null, UTF_8,
                this);
        document.close();
    }


    /** 解决转换pdf的时候,中文无法显示的问题 **/
    @Override
    public Font getFont(String fontname, String encoding, float size, int style) {
        if (fontname == null) {
            fontname = "fangsong";
        }
        return super.getFont(fontname, encoding, size, style);
    }
}
